import axios from 'axios'
import {
  Message,
  MessageBox,
  Loading
} from 'element-ui'
import localStorages from '@/utils/ControlTheCache'
import store from '@/store'
import router from '@/router'

const timeout = 40000, times = 200;
const TIMEOUT_COUNT = 'TIMEOUT_COUNT'; // 统计超时次数
const base = process.env.BASE_API;
const loginBaseApi = process.env.Login_BASE_API;

/*
*  过滤5s内相同的错误提示
* */
const filterSameErrMsg = (function() {
  const errMsgObj = {};
  const EXPIRE = 5 * 1000;
  return {
    filter: function(res) {
      let hit = false;
      const now = new Date();
      Object.keys(errMsgObj).forEach(key => {
        if (key === '00010401' || key === '00010402') { // 这两个过时登录的特殊处理, 不在5s内删除
          if (key === res.code) {
            hit = true;
          }
        } else if (now - errMsgObj[key] > EXPIRE) {
          delete errMsgObj[key];
        } else {
          if (key === res.code) {
            hit = true;
          }
        }
      })
      if (!hit) {
        errMsgObj[res.code] = now;
      }
      return hit;
    },
    delete: function(res) {
      delete errMsgObj[res.code];
    }
  }
})();
const service = axios.create({
  baseURL: '', // api的base_url
  headers: {
    'content-type': 'application/json;charset=UTF-8'
  }
});
let loadingInstance = {
    close: function() {}
  },
  keep = 0,
  interval = [],
  tiemIs = 0;

function common() {
  if (tiemIs > 0) {
    if (keep === 0) {
      loadingInstance.close();
      tiemIs = 0;
      loadingInstance.lock = true;
    }
  } else {
    setTimeout(function() {
      if (keep === 0) {
        loadingInstance.close();
        tiemIs = 0;
        loadingInstance.lock = true;
      }
    }, times)
  }
}
service.interceptors.request.use(config => {
  tiemIs = 0;
  keep++;
  if (!config.params || (config.params && !config.params.noLodaing)) {
    /* 请求效果*/
    loadingInstance = Loading.service({
      lock: true,
      text: '请求正在处理……稍后提示！',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    setTimeout(() => {
      loadingInstance.close();
    }, 5000);
  }

  if (config.params && config.params.noLodaing) {
    delete config.params.noLodaing;
  }

  if (!config.url.includes(loginBaseApi) || !loginBaseApi) {
    config.url = base + config.url;
  }
  if (!config.headers['Authorization']) {
    if (store.getters.token) {
      config.headers['Authorization'] = store.getters.token;
    } else {
      const needToken = !(config.params && config.params.NO_TOKEN);
      if (needToken && !config.url.includes('api/v1/login')) {
        // 非登录接口
        store.dispatch('logOut').then(() => {
          router.replace({ path: '/login' });
        })
      }
    }
  }

  if (config.method === 'post') {
    config.data = config.params || {};
    const { current, size } = config.data;
    config.params = '';
    if (current && size) {
      const urlParams = `current=${current}&size=${size}`;
      config.url += config.url.indexOf('?') > -1 ? ('&' + urlParams) : ('?' + urlParams);
    }
  }
  if (config.method === 'put' || config.method === 'delete') {
    config.data = config.params;
  }
  return config
}, error => {
  Promise.reject(error)
})

service.interceptors.response.use(
  response => {
    keep--;
    if (keep === 0) {
      /* 清空超时定时器*/
      localStorages.set(TIMEOUT_COUNT, 0);
    }
    const res = response.data;
    const has = filterSameErrMsg.filter(res); // 是否5s内提示过
    if (res.code === '00010401' || res.code === '00010402') {
      const isLoginPage = location.hash.includes('login');
      !isLoginPage && !has && MessageBox.confirm('登录凭证已过期,即将跳转到登录页', '确定登出', {
        confirmButtonText: '重新登录',
        showCancelButton: false,
        closeOnClickModal: false,
        type: 'warning'
      }).then(async() => {
        store.dispatch('logOut').then(() => {
          router.replace({ path: '/login' });
        })
      }).catch(() => {
        filterSameErrMsg.delete(res);
      });
    } else if (res.code !== '00000000' && res.msg !== undefined) {
      !has && Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    common();
    return res
  },
  error => {
    keep--;
    loadingInstance.close();
    tiemIs = 0;
    loadingInstance.lock = true;
    if (error === 'Error: timeout of ' + timeout + 'ms exceeded') {
      /* 超时提示*/
      MessageBox.confirm(localStorages.get(TIMEOUT_COUNT) < 2 ? '网络超时，请重新操作！' : '网络多次超时，请检查网络是否正常！', '超时提示', {
        confirmButtonText: '关闭',
        showCancelButton: false,
        closeOnClickModal: false,
        showClose: true,
        type: 'warning'
      });
      /* 记录超时*/
      let times = localStorages.get(TIMEOUT_COUNT);
      localStorages.set(TIMEOUT_COUNT, ++times);
    } else {
      MessageBox.confirm(error.message, '接口请求出错', {
        confirmButtonText: '关闭',
        showCancelButton: false,
        closeOnClickModal: false,
        showClose: true,
        type: 'warning'
      }).then(() => {
        /*        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })*/
      })
    }
    return Promise.reject(error)
  });
window.req = service
export default service
